﻿using System;
using System.Xml;
using System.Collections.Generic;

namespace Genko.Model.Integration.Xml
{
	internal class XmlMemberReader : AbstractMemberReader
	{
		protected XmlMemberReader ownerReader = null;
		protected XmlNode xmlNode = null;
		
		public XmlMemberReader(XmlNode xmlNode)
		{
			this.xmlNode = xmlNode;
		}

		public XmlMemberReader(XmlMemberReader owner, XmlNode xmlNode)
		{
			this.ownerReader = owner;
			this.xmlNode = xmlNode;
		}

		public override IMemberReader OwnerReader
		{
			get { return this.ownerReader; }
		}

		public override Guid? GUID
		{
			get {
				XmlAttribute attr = xmlNode.Attributes[Member.GUID_ATTRIBUTE];
				if (attr != null) {
					return new Guid(attr.Value);
				}
				return null;
			}
		}

		public override string TagName
		{
			get { return xmlNode.Name; }
		}

		public override string Value
		{
			get { return xmlNode.Value; }
		}

		public override int MemberCount
		{
			get { 
				int count = 0;
				foreach (XmlNode node in xmlNode.ChildNodes) {
					if (node.NodeType == XmlNodeType.Element) {
						count++;
					}
				}
				return count;
			}
		}

		public override Dictionary<string, string> ReadAttributes()
		{
			Dictionary<string, string> attributes = new Dictionary<string,string>();
			foreach (XmlAttribute attr in xmlNode.Attributes) {
				if (!string.Equals(attr.Name, Member.GUID_ATTRIBUTE)) {
					attributes.Add(attr.Name, attr.Value);
				}
			}
			return attributes;
		}

		public override IMemberReader ReadMember(int index)
		{
			int elIndex = -1;
			XmlNodeList nodeList = xmlNode.ChildNodes;
			XmlNode node = null;
			for (int i = 0; i < nodeList.Count; i++) {
				node = nodeList[i];
				if (node.NodeType == XmlNodeType.Element) {
					elIndex++;
					if (elIndex == index) {
						return new XmlMemberReader(this, node);
					}
				}
			}
			return null;
		}
	}
}
